// scripts/buildSyntaxDiagrams.ts
import fs from 'fs';
import path from 'path';
import { convertEbnfToDiagram } from './syntaxDiagram';

interface EbnfFile {
  id: string;
  content: string;
  hash: string;
}

// 简单的哈希函数
function simpleHash(str: string): string {
  let hash = 0;
  for (let i = 0; i < str.length; i++) {
    const char = str.charCodeAt(i);
    hash = ((hash << 5) - hash) + char;
    hash = hash & hash; // 转换为32位整数
  }
  return Math.abs(hash).toString(36);
}

// 扫描 EBNF 文件
function scanEbnfFiles(dir: string): EbnfFile[] {
  const files: EbnfFile[] = [];
  
  function scan(currentDir: string) {
    if (!fs.existsSync(currentDir)) return;
    
    const items = fs.readdirSync(currentDir);
    
    for (const item of items) {
      const fullPath = path.join(currentDir, item);
      const stat = fs.statSync(fullPath);
      
      if (stat.isDirectory()) {
        scan(fullPath);
      } else if (item.endsWith('.ebnf') || item.endsWith('.txt')) {
        const content = fs.readFileSync(fullPath, 'utf-8');
        const id = path.relative(dir, fullPath).replace(/\.(ebnf|txt)$/, '');
        const hash = simpleHash(content);
        files.push({ id, content, hash });
      }
    }
  }
  
  scan(dir);
  return files;
}

// 构建语法图
function buildSyntaxDiagrams() {
  const ebnfDir = path.join(process.cwd(), 'src/ebnf');
  const outputDir = path.join(process.cwd(), 'public/syntax-diagrams');
  
  // 确保输出目录存在
  if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir, { recursive: true });
  }
  
  const ebnfFiles = scanEbnfFiles(ebnfDir);
  const diagrams: Record<string, { html: string; hash: string }> = {};
  
  
  for (const file of ebnfFiles) {
    try {
      const diagramHtml = convertEbnfToDiagram(file.content);
      diagrams[file.id] = {
        html: diagramHtml,
        hash: file.hash
      };
      
    } catch (error) {
      console.error(`✗ Error processing ${file.id}:`, error);
    }
  }
  
  // 保存索引文件
  const indexPath = path.join(outputDir, 'index.json');
  fs.writeFileSync(indexPath, JSON.stringify(diagrams, null, 2));
  
}

// 如果直接运行此文件
if (require.main === module) {
  buildSyntaxDiagrams();
}

export { buildSyntaxDiagrams };